package com.i8office.android.zhihuixinwu.ui.schedule;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseActivity;
import com.example.menhoo.toollibrary.common.utils.DisplayUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.event.ChooseMeetingEvent;
import com.i8office.android.zhihuixinwu.event.RefreshCalendarEvent;
import com.i8office.android.zhihuixinwu.module.contract.CalendarContract;
import com.i8office.android.zhihuixinwu.module.presenter.AddEventPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import view.recyclerview.CommonAdapter;
import view.recyclerview.ViewHolder;

@ActivityFragmentInject(contentViewId = R.layout.activity_add_leader_event)
public class AddLeaderEventActivity extends BaseActivity<CalendarContract.AddEventPresenter> implements CalendarContract.AddEventView {
    @BindView(R.id.tv_date)
    TextView mDate;
    @BindView(R.id.tv_time)
    AppCompatEditText mTime;
    @BindView(R.id.et_leader)
    AppCompatEditText mLeader;
    @BindView(R.id.title)
    TextView mTvTitle;
    @BindView(R.id.tv_apm)
    TextView mTvApm;
    @BindView(R.id.et_title)
    AppCompatEditText mTitle;
    @BindView(R.id.delete)
    AppCompatButton mDelete;
    @BindView(R.id.et_location)
    AppCompatEditText mLocation;
    @BindView(R.id.edit_hint)
    TextView mEditHint;
    @BindView(R.id.submit)
    TextView mSubmit;
    @BindView(R.id.et_dept)
    AppCompatEditText mDept;
    @BindView(R.id.choose_meetting)
    View mChooseMeetting;
    private EventItem eventItem;
    private MaterialDialog remindDialog;
    private int timeQuantum = 1;
    private Meetting meetting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new AddEventPresenter(this);
        eventItem = (EventItem) getIntent().getSerializableExtra("event");
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setDrawableLeft(mDate, R.drawable.icon_date);
        setDrawableLeft(mTime, R.drawable.icon_time);
        setDrawableLeft(mLocation, R.drawable.icon_location);
        setDrawableLeft(mTvApm, R.drawable.icon_bq);
        setDrawableLeft(mDept, R.drawable.icon_department);
        setDrawableLeft(mLeader, R.drawable.icon_join_leaders);
        mTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    int hour = 0;
                    int minute = 0;
                    String startTime = mTime.getText().toString().replace(":", "");
                    if (!TextUtils.isEmpty(startTime)) {
                        try {
                            if (startTime.length() != 4) {
                                mTime.setText("");
                                toast("时间格式不正确");

                                return;
                            }
                            hour = Integer.parseInt(startTime.substring(0, 2));
                            minute = Integer.parseInt(startTime.substring(2, 4));
                            if (hour > 24 || hour < 0 || minute >= 60 || minute < 0) {
                                mTime.setText("");
                                toast("时间格式不正确");

                                return;
                            }
                            mTime.setText(startTime.substring(0, 2) + ":" + startTime.substring(2, 4));
                        } catch (Exception e) {
                            mTime.setText("");
                            toast("时间格式不正确");

                            return;
                        }
                    }
                } else {
                    String startTime = mTime.getText().toString().replace(":", "");
                    mTime.setText(startTime);
                }
            }
        });
        if (eventItem != null) {
//            if (eventItem.getCanEdit() == 0) {
//                mTitle.setEnabled(false);
//                mDate.setEnabled(false);
//                mTime.setEnabled(false);
//                mTvApm.setEnabled(false);
//                mLocation.setEnabled(false);
//                mDept.setEnabled(false);
//                mLeader.setEnabled(false);
//                mEditHint.setVisibility(View.VISIBLE);
//                mEditHint.setText("提示："+eventItem.getDesc());
//                mSubmit.setVisibility(View.GONE);
//            }
//            else {
//                mEditHint.setVisibility(View.GONE);
//            }
            mChooseMeetting.setVisibility(View.GONE);
            mTitle.setText(eventItem.getTitle());
            mLocation.setText(eventItem.getLocation());
            mDate.setText(eventItem.getStartDateString());
            mLeader.setText(eventItem.getJoinLeaders());
            String[] apms = getResources().getStringArray(R.array.apm);
            timeQuantum = eventItem.getTimeQuantum();
            mTvApm.setText(timeQuantum == 1 ? apms[0] : apms[1]);

            if (TextUtils.isEmpty(eventItem.getStartTimeString()) || eventItem.getStartTimeString().equals("--:--")) {
                mTime.setText("");
            } else {
                mTime.setText(eventItem.getHMTime());
            }
            mDept.setText(eventItem.getDeptName());
            mDelete.setVisibility(View.VISIBLE);
        } else {
//            mEditHint.setVisibility(View.GONE);
            mDate.setText(getIntent().getStringExtra("date"));
        }
        mTvTitle.setText(eventItem == null ? R.string.add_event : R.string.event_detail);
        EventBus.getDefault().register(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChooseMeetting(ChooseMeetingEvent event) {
//        mTitle.setEnabled(false);
//        mDate.setEnabled(false);
//        mTime.setEnabled(false);
//        mTvApm.setEnabled(false);
//        mLocation.setEnabled(false);
//        mDept.setEnabled(false);
//        mLeader.setEnabled(false);
//        mEditHint.setVisibility(View.VISIBLE);
        meetting = event.meetting;
        mTitle.setText(meetting.getTitle());
        mLocation.setText(meetting.getLocation());
        timeQuantum = meetting.getTimeQuantum();
        mTvApm.setText(timeQuantum == 1 ? "上午" : "下午");
        if (meetting.getStartTime() != null && !meetting.getStartTime().getHMTime().equals("00:00")) {
            mTime.setText(meetting.getStartTime().getHMTime());
        } else {
            mTime.setText("");
        }
        mDept.setText(meetting.getDeptName());
    }

    @Override
    public void onDestroy() {
        if (KeyboardUtils.isSoftInputVisible(this)) {
            KeyboardUtils.toggleSoftInput();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void setDrawableLeft(TextView view, @DrawableRes int drawableRes) {
        Drawable drawable = ContextCompat.getDrawable(this, drawableRes);
        drawable.setBounds(0, 0, DisplayUtil.dip2px(this, 30), DisplayUtil.dip2px(this, 30));
        view.setCompoundDrawables(drawable, null, null, null);
    }

    @OnClick({R.id.delete, R.id.tv_date, R.id.tv_apm, R.id.choose_meetting})
    void clickBtn(View view) {
        String startTime = mTime.getText().toString().replace(":", "");
        if (!TextUtils.isEmpty(startTime)) {
            try {
                if (startTime.length() != 4) {
                    mTime.setText("");
                    toast("时间格式不正确");

                    return;
                }
                int hour = Integer.parseInt(startTime.substring(0, 2));
                int minute = Integer.parseInt(startTime.substring(2, 4));
                if (hour > 24 || hour < 0 || minute >= 60 || minute < 0) {
                    mTime.setText("");
                    toast("时间格式不正确");

                    return;
                }
                mTime.setText(startTime.substring(0, 2) + ":" + startTime.substring(2, 4));
            } catch (Exception e) {
                mTime.setText("");
                toast("时间格式不正确");

                return;
            }
        }
        switch (view.getId()) {
            case R.id.delete:
                delete();
                break;
            case R.id.tv_date:
                chooseDate();
                break;
            case R.id.tv_apm:
                chooseApm();
                break;
            case R.id.choose_meetting:
                chooseMeeting();
                break;
        }
    }

    void delete() {
        if (eventItem != null) {
            new MaterialDialog.Builder(this)
                    .content(R.string.delete_event)
                    .positiveText(R.string.confirm)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                            mPresenter.removeEvent(eventItem.getTaskID(), getIntent().getStringExtra("leaderId"));
                        }
                    })
                    .negativeText(R.string.cancel)
                    .show();
        }
    }

    void chooseDate() {
        mTime.clearFocus();
        final Calendar calendar = Calendar.getInstance();
        // 日期对话框
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                calendar.set(year, monthOfYear, dayOfMonth);
                mDate.setText(format.format(calendar.getTimeInMillis()));
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();

    }

    void chooseApm() {
        mTime.clearFocus();
        List<String> items = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.apm)));
        remindDialog = new MaterialDialog.Builder(this)
                .adapter(new CommonAdapter<String>(this, R.layout.item_remind, items) {
                    @Override
                    protected void convert(ViewHolder holder, final String s, final int position) {
                        holder.setText(R.id.text, s);

                        holder.getView(R.id.img).setSelected((timeQuantum == 1 ? 0 : 1) == position);
                        holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (position == 0) {
                                    timeQuantum = 1;
                                } else {
                                    timeQuantum = 3;
                                }
                                mTvApm.setText(s);
                                remindDialog.dismiss();
                            }
                        });
                    }
                }, new LinearLayoutManager(this))
                .show();
    }

    void chooseMeeting() {
        mTime.clearFocus();
        Intent intent = new Intent(this, ChooseMeettingActivity.class);
        intent.putExtra("date", mDate.getText().toString());
        intent.putExtra("leaderId", getIntent().getStringExtra("leaderId"));
        startActivity(intent);
    }

    @OnClick(R.id.submit)
    void submit() {
        //确定提交
        if (eventItem != null) {
            updateEvent();
        } else {
            addEvent();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return false;
    }

    //添加日程
    private void addEvent() {
        String title = mTitle.getText().toString();
        String startDate = mDate.getText().toString();
        String startTime = mTime.getText().toString().replace(":", "");
        String location = mLocation.getText().toString();
        String deptName = mDept.getText().toString();
        String joinLeaders = mLeader.getText().toString();

        if (TextUtils.isEmpty(title)) {
            toast(R.string.title_error);
            return;
        }
        if (TextUtils.isEmpty(startDate)) {
            toast(R.string.start_date_error);
            return;
        }
        Map<String, String> params = new HashMap<>();
        int hour = 0;
        int minute = 0;
        if (!TextUtils.isEmpty(startTime)) {
            try {
                if (startTime.length() != 4) {
                    toast("时间格式不正确");
                    return;
                }
                hour = Integer.parseInt(startTime.substring(0, 2));
                minute = Integer.parseInt(startTime.substring(2, 4));
                if (hour > 24 || hour < 0 || minute >= 60 || minute < 0) {
                    toast("时间格式不正确");
                    return;
                }
                params.put("hour", String.valueOf(hour));
                params.put("minute", String.valueOf(minute));
            } catch (Exception e) {
                toast("时间格式不正确");
                return;
            }

        } else {
            params.put("hour", "");
            params.put("minute", "");
        }
        params.put("timeQuantum", String.valueOf(timeQuantum));
        params.put("title", title);
        params.put("startDate", startDate);
        params.put("location", location);
        params.put("deptName", deptName);
        params.put("leaderId", getIntent().getStringExtra("leaderId"));
        params.put("dayOffset", "");
        params.put("hourOffset", "");
        params.put("minuteOffset", "");
        params.put("joinLeaders", joinLeaders);
        params.put("referrerTaskId", meetting == null ? "" : meetting.getTaskID());
        mPresenter.addEvent(params);
    }

    //修改日程
    private void updateEvent() {
        String title = mTitle.getText().toString();
        String startDate = mDate.getText().toString();
        String startTime = mTime.getText().toString().replace(":", "");
        String location = mLocation.getText().toString();
        String deptName = mDept.getText().toString();
        String joinLeaders = mLeader.getText().toString();

        if (TextUtils.isEmpty(title)) {
            toast(R.string.title_error);
            return;
        }
        if (TextUtils.isEmpty(startDate)) {
            toast(R.string.start_date_error);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("id", eventItem.getTaskID());

        if (!TextUtils.isEmpty(startTime)) {
            try {
                if (startTime.length() != 4) {
                    toast("时间格式不正确");
                    return;
                }

                int hour = Integer.parseInt(startTime.substring(0, 2));
                int minute = Integer.parseInt(startTime.substring(2, 4));
                if (hour > 24 || hour < 0 || minute >= 60 || minute < 0) {
                    toast("时间格式不正确");
                    return;
                }
//                if (hour == 12 && timeQuantum == 3) {
//                    toast("12点之后只能选上午或中午");
//                    return;
//                }
                params.put("hour", String.valueOf(hour));
                params.put("minute", String.valueOf(minute));
            } catch (Exception e) {
                toast("时间格式不正确");
                return;
            }
        } else {
            params.put("hour", "");
            params.put("minute", "");
        }

        params.put("timeQuantum", String.valueOf(timeQuantum));
        params.put("title", title);
        params.put("startDate", startDate);
        params.put("location", location);
        params.put("deptName", deptName);
        params.put("leaderId", getIntent().getStringExtra("leaderId"));
        params.put("dayOffset", "");
        params.put("hourOffset", "");
        params.put("minuteOffset", "");
        params.put("joinLeaders", joinLeaders);
        if (eventItem != null && eventItem.getCanEdit() == 0) {
            mPresenter.updateOtherEvent(params);
        } else {
            mPresenter.updateEvent(params);
        }
//        String startDate = mDate.getText().toString();
//        String title = mTitle.getText().toString();
////        int timeQuantum = apm;
//        String location = mLocation.getText().toString();
//        int hour = sH;
//        int minute = sM;
//
//        if (TextUtils.isEmpty(title)) {
//            toast(R.string.title_error);
//            return;
//        }
//        if (TextUtils.isEmpty(startDate)) {
//            toast(R.string.start_date_error);
//            return;
//        }
//        if (TextUtils.isEmpty(mTime.getText().toString()) && !TextUtils.isEmpty(mRemind.getText().toString())) {
//            toast(R.string.remind_time_error);
//            return;
//        }
//        Map<String, String> params = new HashMap<>();
//        params.put("id", eventItem.getTaskID());
//        params.put("startDate", startDate);
//        params.put("title", title);
////        params.put("timeQuantum", String.valueOf(timeQuantum));
//        params.put("location", location);
//        if (!TextUtils.isEmpty(mTime.getText().toString())) {
//            params.put("hour", String.valueOf(hour));
//            params.put("minute", String.valueOf(minute));
//        } else {
//            params.put("hour", "");
//            params.put("minute", "");
//        }
//
//        params.put("dayOffset", "");
//        params.put("hourOffset", "");
//        params.put("minuteOffset", "");
//        mPresenter.updateEvent(params);
    }


    @Override
    public void addSuccess() {
        //添加成功刷新列表和日历
        EventBus.getDefault().post(new RefreshCalendarEvent());
        finish();
    }

    @Override
    public void deleteSuccess() {
        addSuccess();
    }

    @Override
    public void showProgress() {
    }

    @Override
    public void hideProgress() {

    }
}
